'use strict';

// uni.setStorageSync('token','eyJhbGciOiJIUzI1NiJ9.eyJzZWxsZXJJZCI6NjUsIm9ubGluZU1hcmsiOiIxNzAyODg5MzUzOTQwIiwiY2FyTWVtYmVySWQiOjExMzY1LCJpc0xlYWd1ZXIiOjAsImxlYWd1ZXJJZCI6MiwidHlwZSI6IjEiLCJleHAiOjE3MzQ1MTE3NTMsInBob25lTm8iOiIxNTg3ODk3NTQ4MCIsIm1lbWJlcklkIjoxMTM1NH0.tMV3rung1GvkeOLaZIcyTwiau1Fgkuvrtt0WX5jWt3A')

var __awaiter =
	(this && this.__awaiter) ||
	function(thisArg, _arguments, P, generator) {
		return new(P || (P = Promise))(function(resolve, reject) {
			function fulfilled(value) {
				try {
					step(generator.next(value));
				} catch (e) {
					reject(e);
				}
			}

			function rejected(value) {
				try {
					step(generator['throw'](value));
				} catch (e) {
					reject(e);
				}
			}

			function step(result) {
				result.done ?
					resolve(result.value) :
					new P(function(resolve) {
						resolve(result.value);
					}).then(fulfilled, rejected);
			}

			step((generator = generator.apply(thisArg, _arguments || [])).next());
		});
	};

var __generator =
	(this && this.__generator) ||
	function(thisArg, body) {
		var _ = {
				label: 0,
				sent: function() {
					if (t[0] & 1) throw t[1];
					return t[1];
				},
				trys: [],
				ops: []
			},
			f,
			y,
			t,
			g;
		return (
			(g = {
				next: verb(0),
				throw: verb(1),
				return: verb(2)
			}),
			typeof Symbol === 'function' &&
			(g[Symbol.iterator] = function() {
				return this;
			}),
			g
		);

		function verb(n) {
			return function(v) {
				return step([n, v]);
			};
		}

		function step(op) {
			if (f) throw new TypeError('Generator is already executing.');

			while (_)
				try {
					if (((f = 1), y && (t = op[0] & 2 ? y['return'] : op[0] ? y['throw'] || ((t = y['return']) && t
							.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done))
						return t;
					if (((y = 0), t)) op = [op[0] & 2, t.value];

					switch (op[0]) {
						case 0:
						case 1:
							t = op;
							break;

						case 4:
							_.label++;
							return {
								value: op[1],
									done: false
							};

						case 5:
							_.label++;
							y = op[1];
							op = [0];
							continue;

						case 7:
							op = _.ops.pop();

							_.trys.pop();

							continue;

						default:
							if (!((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && (op[0] === 6 || op[0] ===
									2)) {
								_ = 0;
								continue;
							}

							if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
								_.label = op[1];
								break;
							}

							if (op[0] === 6 && _.label < t[1]) {
								_.label = t[1];
								t = op;
								break;
							}

							if (t && _.label < t[2]) {
								_.label = t[2];

								_.ops.push(op);

								break;
							}

							if (t[2]) _.ops.pop();

							_.trys.pop();

							continue;
					}

					op = body.call(thisArg, _);
				} catch (e) {
					op = [6, e];
					y = 0;
				} finally {
					f = t = 0;
				}

			if (op[0] & 5) throw op[1];
			return {
				value: op[0] ? op[1] : void 0,
				done: true
			};
		}
	};

exports.__esModule = true;
var util_1 = require("../utils/util");
var globalData_1 = require("../globalData");
console.log(globalData_1, 'globalData_1globalData_1')
var debounce = new util_1.Debounce();
var HttpMethod;

(function(HttpMethod) {
	HttpMethod['OPTIONS'] = 'OPTIONS';
	HttpMethod['GET'] = 'GET';
	HttpMethod['HEAD'] = 'HEAD';
	HttpMethod['POST'] = 'POST';
	HttpMethod['PUT'] = 'PUT';
	HttpMethod['DELETE'] = 'DELETE';
	HttpMethod['TRACE'] = 'TRACE';
	HttpMethod['CONNECT'] = 'CONNECT';
})(HttpMethod || (HttpMethod = {}));
import { toLogin } from '../utils/util';
var request =
	/** @class */
	(function() {
		function request(options) {
			var _this_1 = this;
			// 接口500报错处理白名单
			this.whiteErrorApis = ['querChargeOnline','currentTemplateId','getWechatMiniProgramTemplateId','disposable/orderResultQuery','privatePileShareReservation/reservation','myBillDetails']
			// GET类型的网络请求
			this.getRequest = function(param, loop) {
				return _this_1.requestAll(param, loop);
			};
			// POST类型的网络请求
			this.postRequest = function(param, loop) {
				param = Object.assign(param, {
					method: HttpMethod['POST']
				});
				return _this_1.requestAll(param, loop);
			};
			//DELETE类型的网络请求
			this.deleteRequest=function(param, loop) {
				param = Object.assign(param, {
					method: HttpMethod['DELETE']
				});
				return _this_1.requestAll(param, loop);
			};
			
			
			this.requestAll = function(param, loop) {
				if (loop === void 0) {
					loop = false;
				}

				return __awaiter(_this_1, void 0, void 0, function() {
					var _this, isMarketing, errMsg, Token, data, url, header;

					return __generator(this, function(_a) {
						_this = this;
						isMarketing = _this._isMarketing;
						errMsg = isMarketing ? '营销获客服务端接口报错' : '服务端接口报错';
						Token = uni.getStorageSync('token');
						
						data = param.data || {};

						if (Object.prototype.toString.call(data) == "[object Object]" &&
							isMarketing) {
							if (!data.plUserId) {
								data.plUserId = uni.getStorageSync('memberId');
							}
							if (!data.userId) {
								data.userId = uni.getStorageSync('memberId');
							}
						}

						if (_this._options && _this._options.ApiUrl) {
							url = _this._options.ApiUrl + '/' + param.url
						} else {
							url = globalData_1["default"].URL + '/api-service/api/' + param.url
						}
						header = _this._header(param.header || 'json');
						
						if(isMarketing && !globalData_1["default"].marketingSwitch){
							// console.error('Error:营销获客开关未开启')
							return [2,Promise.reject({})]
						}
						return [
							2,
							/*return*/
							new Promise(function(resolve, reject) {
								let requestTask = uni.request({
									url: url,
									data: data,
									header: header,
									method: param.method || HttpMethod['GET'],
									success: function(res) {
										//这里可以根据自己项目服务端定义的正确的返回码来进行，接口请求成功后的处理，当然也可以在这里进行报文加解密的统一处理
										param.isLoading && util_1.hideLoading();
										// 设置Cookie
										var cookie = res.header[
											"Set-Cookie"];
										cookie && uni.setStorageSync(
											"cookie", cookie);

										if (res.statusCode === 200) {
											var datas = res.data;
											// 判断是否请求pc的接口，是的话判断是否请求验证码接口，拿到响应请求头的验证码并返回结果
										
											if (~param.url.indexOf(
													'user/verifyCode')) {
														console.log('走到这里了哈哈哈',res,res?.header?.Logincaptcha,res?.header?.loginCaptcha)
												return resolve(res?.header?.Logincaptcha || res?.header?.loginCaptcha || null);
												// }
											}
											
											// 白名单内直接返回，不走code 500报错页面
											if(_this_1.whiteErrorApis.find(item=> param.url.indexOf(item) >= 0)){
												console.log('白名单内拉',param.url)
												resolve(datas);
												return;
											}

											if (datas.code === 0 || datas
												.code === 7 || datas
												.code === 50 || datas
												.code === 1020100123 ||
												datas.code === 5) {
												//50:未注册
												resolve(datas);

												if (param.url ===
													'getMemberInfo') {
													// 账号禁用
													if (datas.data
														.memberStatus === 4
													) {
														var phoneNumber_1 =
															getApp()
															.globalData
															.telNum;

														if (phoneNumber_1) {
															uni.showModal({
																title: '提示',
																content: '\u60A8\u7684\u8D26\u6237\u5B58\u5728\u5F02\u5E38\uFF0C\u73B0\u5DF2\u88AB\u505C\u7528\uFF0C\u5982\u9700\u89E3\u5C01\u8BF7\u8054\u7CFB\u5BA2\u670D\u5904\u7406\uFF01\u5BA2\u670D\u7535\u8BDD\uFF1A' +
																	phoneNumber_1,
																cancelText: '退出',
																confirmText: '呼叫客服',
																success: function(
																	res
																) {
																	if (res
																		.confirm
																	) {
																		uni.makePhoneCall({
																			phoneNumber: phoneNumber_1
																		});
																	} else if (
																		res
																		.cancel
																	) {
																		uni
																			.exitMiniProgram();
																	}
																}
															});
														} else {
															uni.showModal({
																title: '提示',
																content: '\u60A8\u7684\u8D26\u6237\u5B58\u5728\u5F02\u5E38\uFF0C\u73B0\u5DF2\u88AB\u505C\u7528\uFF0C\u5982\u9700\u89E3\u5C01\u8BF7\u8054\u7CFB\u5BA2\u670D\u5904\u7406\uFF01',
																showCancel: false,
																confirmText: '退出',
																success: function(
																	res
																) {
																	if (res
																		.confirm
																	) {
																		uni
																			.exitMiniProgram();
																	}
																}
															});
														}
													}
												}
											}else if (datas.code === -2) {
												//订单数据异常
												resolve(datas);
											} else if (datas.code === -1) {
												//未登陆
												 toLogin('当前未登陆，请重新授权')
											} else if (datas.code === 1) {
												//鉴权失败
												 toLogin('鉴权失败，请重新授权')
											} else if (datas.code === 2) {
												//Token失效
												toLogin('登录过期，请重新授权')

											} else if (datas.code === 3) {
												//参数异常\
												resolve(datas);
											} else if (datas.code === 4) {
												//数据不存在
												resolve(datas);
											}else if (datas.code === 6000) {
												//该微信关联了其他手机号码
												resolve(datas);
											}

											else if (datas.code === 8) {
												//pc密码错误
												resolve(datas);
											}
											// else if (datas.code === 5) {
											//数据异常
											// uni.showModal({
											// 	title: '信息提示',
											// 	content: datas.msg,
											// 	showCancel: false
											// });
											// if(getCurrentPages()[getCurrentPages().length - 1].route !== 'pages/errorPage/index'){
											// 	uni.navigateTo({
											// 		url: '/pages/errorPage/index?code=501'
											// 	});
											// }
											// }
											else if (datas.code === 6) {
												//维护中
												uni.showModal({
													title: '信息提示',
													content: datas
														.msg,
													showCancel: false
												});
												if (getCurrentPages()[
														getCurrentPages()
														.length - 1]
													.route !==
													'pages/errorPage/index'
												) {
													uni.navigateTo({
														url: '/pages/errorPage/index?code=501'
													});
												}
											} else if (datas.code === 9) {
												//身份权限不足
												uni.showModal({
													title: '信息提示',
													content: datas
														.msg,
													showCancel: false
												});
											} else if (datas.code === 7) {
												//未注册的用户
												uni.showModal({
													title: '信息提示',
													content: datas
														.msg,
													showCancel: false
												});
											} else if (datas.code === 401
											) { 
												resolve(datas);
											} else if (datas.code === 12) {
												// 密码登录-用户不存在
												resolve(datas);
											} else if (datas.code ===
												1004) {
												//服务异常
												uni.showModal({
													title: '信息提示',
													content: datas
														.msg,
													showCancel: false
												});
											} else if (datas.code === 500) {
												//服务异常
												resolve(datas);
												console.error('报错API：', url)
												uni.showToast({
													title: '服务异常',
													icon: 'error',
													duration: 2000
												});
												if (getCurrentPages()[
														getCurrentPages()
														.length - 1]
													.route !==
													'pages/errorPage/index'
												) {
													uni.navigateTo({
														url: '/pages/errorPage/index?code=501'
													});
												}
											} else if (datas.code === 501) {
												//充值失败
												reject(datas);
											} else if (datas.code === 502) {
												//请求错误
												uni.showModal({
													title: '信息提示',
													content: datas
														.msg,
													showCancel: false
												});
											} else if (datas.code ===
												1020100022) {
												//登录失败,商家已经停用
												uni.showModal({
													title: '消息提示',
													content: '登录失败,商家已经停用',
													confirmText: '确定',
													showCancel: false,
													success: function() {
														uni.navigateTo({
															url: '/packagePersonal/pages/login/login'
														});
													}
												});
											} else if (datas.code ===
												1020100024) {
												//会员存在多身份
												uni.showModal({
													title: '消息提示',
													content: '会员存在多身份',
													confirmText: '确定',
													showCancel: false,
													success: function() {
														uni.navigateTo({
															url: '/packagePersonal/pages/login/login'
														});
													}
												});
											} else if (datas.code ===
												1020100003) {
												//登录失败，该会员不属于此商家
												uni.showModal({
													title: '消息提示',
													content: '登录失败，该会员不属于此商家',
													confirmText: '确定',
													showCancel: false,
													success: function() {
														uni.navigateTo({
															url: '/packagePersonal/pages/login/login'
														});
													}
												});
											} else if (datas.code ===
												50501) {
												// 枪号启动异常
												resolve(datas);
											} else {

												resolve(datas);
												// 营销获客服务不报错
												if (!isMarketing) {
													// uni.showToast({
													// 	title: datas
													// 		.msg,
													// 	icon: 'none',
													// })
												}
											}
										} else {
											reject({
												msg: errMsg,
												code: 5001,
												isMarketing: isMarketing
											});
										}
									},
									fail: function() {
										var pages = getCurrentPages();
										var currPage = pages[pages.length -
											1];

										// if (currPage.route ===
										// 	'pages/index/index') {
										// 	setTimeout(function() {
										// 		_this.requestAll(
										// 			param);
										// 	}, 1000);
										// }
										
										//   判断是否营销获客的接口
										// if (isMarketing) {
										// 	//   设置营销获客的接口服务奔溃
										// 	uni.setStorageSync(
										// 		'marketingSwitch',
										// 		true);
										// 	util_1
										// 		.setCurrentPagemarketingSwitch();
										// }
										reject({
											msg: errMsg,
											code: 5000,
											isMarketing: isMarketing
										});
									},
									complete: () => {
										//uni.hideLoading();
									}
								});
								if (param.enableCancel) {
									// 将当前请求存入全局对象里
									getApp().globalData.requestTasks.push(requestTask)
							}
							})
						];
					});
				});
			};

			this._options = options || {};
			this._isMarketing = this._options.ApiUrl == globalData_1["default"].marketingUrl;

			this._header = function(type) {
				var token = _this_1._isMarketing ? uni.getStorageSync('token') : uni.getStorageSync(
					'token');
				var cookie = uni.getStorageSync("cookie") || ''
				var data = {
					'Authorization': token,
					'cookie': cookie
				}
				if (!cookie) {
					delete data.cookie
				}
				if (typeof type === 'string') {
					if (type === 'form') {
						data['content-type'] = 'application/x-www-form-urlencoded'
						return data;
					} else {
						data['content-type'] = 'application/json'
						return data;
					}
				} else {
					return type;
				}
			};

			this._loading = function(that) {
				return function() {
					that.setData({
						myComponentData: {
							pagestate: {
								show: true,
								state: 'loading',
								message: '加载中'
							}
						}
					});
				};
			};

			this._error = function(that, message) {
				if (message === void 0) {
					message = '网络连接异常~';
				}

				return function() {
					that.setData({
						myComponentData: {
							pagestate: {
								show: true,
								state: 'error',
								message: message
							}
						}
					});
				};
			};

			this._empty = function(that, message) {
				if (message === void 0) {
					message = '空空如也';
				}

				return function() {
					that.setData({
						myComponentData: {
							pagestate: {
								show: true,
								state: 'empty',
								message: message
							}
						}
					});
				};
			};

			this._finish = function(that) {
				return function() {
					setTimeout(function() {
						that.setData({
							myComponentData: {
								pagestate: {
									show: false,
									state: 'finish',
									message: ''
								}
							}
						});
					}, 300);
				};
			};

			this._maintain = function(that, message) {
				if (message === void 0) {
					message = '页面维护中';
				}

				return function() {
					that.setData({
						myComponentData: {
							pagestate: {
								show: true,
								state: 'maintain',
								message: message
							}
						}
					});
				};
			};
		}
		/*
设置统一的异常处理
handler: { // 接口异常操作类型
	type: Array,
	value: [], // func:页面自定义事件, custom:自定义提示弹窗, navigateBack:回退页面, redirectTo:页面跳转, methods:执行事件
},
handleData: { // 接口异常操作类型值
	type: Object,
	value: {}, // key是handler(接口异常操作类型)的值, value是对应的操作。 methods: [事件1, 事件2, ...]
},
*/

		request.prototype.setErrorHandler = function(handler, handleData, that) {
			if (handler === void 0) {
				handler = [];
			}

			if (handleData === void 0) {
				handleData = {};
			}

			var _this = this;

			if (handler.includes('func')) {
				_this._errorHandler = handleData.func;
			} else {
				_this._errorHandler = function(datas) {
					if (handler.includes('custom')) {
						console.log('_errorHandler custom');
					} else {
						uni.showModal({
							title: '提示',
							content: datas.error.msg || datas.error || '接口返回报错信息异常',
							confirmColor: '#09BB07',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									if (handler.includes('navigateBack')) {
										uni.navigateBack();
									} else if (handler.includes('redirectTo')) {
										uni.redirectTo({
											url: handleData.redirectTo
										});
									} else if (handler.includes('methods')) {
										handleData.methods.forEach(function(item) {
											item();
										});
									}
								}
							}
						});
					}

					_this._errorHandler = undefined;
				};
			}
		}; // 页面状态

		request.prototype.pageState = function(that) {
			return {
				loading: this._loading(that),
				error: this._error(that),
				empty: this._empty(that),
				finish: this._finish(that),
				maintain: this._maintain(that)
			};
		};
		/*
初始化页面检测网络:
handle: ['no_maintain'], //no_maintain: 页面不维护
*/

		request.prototype.initPage = function(that, handle, handleData) {
			if (handle === void 0) {
				handle = [];
			}

			if (handleData === void 0) {
				handleData = {};
			}

			var _this = this;

			return new Promise(function(resolve, reject) {
				if (!handle.includes('no_maintain') && uni.getStorageSync('cloud_shop_business') ===
					'1' && uni.getStorageSync('is_banning_orders') === '1') {
					_this.pageState(that).maintain();

					reject('商城维护中');
				} else {
					uni.getNetworkType({
						success: function(res) {
							//返回网络类型, 有效值： wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
							if (res.networkType == 'none') {
								reject('网络连接异常~');
							} else {
								resolve(false);
							}
						}
					});
				}
			});
		}; // 判断网络

		request.prototype.judgeNet = function(that) {
			var _this = this;

			return new Promise(function(resolve, reject) {
				uni.getNetworkType({
					success: function(res) {
						//返回网络类型, 有效值： wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
						if (res.networkType == 'none') {
							uni.showModal({
								title: '提示',
								content: '请检查网络连接',
								confirmColor: '#09BB07',
								showCancel: false
							});
							resolve(false);
						} else {
							_this.pageState(that).loading();

							resolve(true);
						}
					},
					fail: function() {
						uni.showModal({
							title: '提示',
							content: '请检查网络连接',
							confirmColor: '#09BB07',
							showCancel: false
						});
						resolve(false);
					}
				});
			});
		};

		return request;
	})();

exports['default'] = request; // app.request.postRequest('/index.php?act=goods_class&op=index', {}).then((res)=>{
//   console.log(res);
//   app.request.pageState(that).maintain();
// }).catch((err)=>{
// });
